import React, { useMemo, useState } from 'react';
import { NodeProps } from 'reactflow';
import { useContextSelector } from 'use-context-selector';

import CollapsibleSection from '@/components/CollapsibleSection';
import { t } from '@/locales/i18n';
import { FlowNodeOutputTypeEnum } from '@/types/workflow/constant';
import { FlowNodeItemType } from '@/types/workflow/node';

import { WorkflowContext } from '../../context';

import NodeCard from './render/NodeCard';
import RenderInput from './render/RenderInput';
import RenderOutput from './render/RenderOutput';
import RenderToolInput from './render/RenderToolInput';

const NodeSimple = ({
  data,
  selected,
  minW = '350px',
  maxW = '600px',
}: NodeProps<FlowNodeItemType> & { minW?: string | number; maxW?: string | number }) => {
  const splitToolInputs = useContextSelector(WorkflowContext, (ctx) => ctx.splitToolInputs);
  const { nodeId, inputs, outputs } = data;

  const [expandedSection, setExpandedSection] = useState<('input' | 'params' | 'output')[]>([
    'input',
  ]);

  const toggleSection = (section: 'input' | 'params' | 'output') => {
    setExpandedSection((prev) =>
      prev.includes(section) ? prev.filter((s) => s !== section) : [...prev, section],
    );
  };

  const Render = useMemo(() => {
    const { isTool, commonInputs } = splitToolInputs(inputs, nodeId);
    const filterHiddenInputs = commonInputs.filter((item) => true);
    const requiredInputs = filterHiddenInputs.filter((item) => item.required);

    // const { invalidCount } = checkInputsValidCount(requiredInputs);

    const requireText = requiredInputs
      .filter((item) => item.label !== '')
      .map((item) => t(item.label as any))
      .join('，');

    const optionalInputs = filterHiddenInputs.filter(
      (item) => !item.required || item.canEdit === true,
    );

    return (
      <NodeCard minW={minW} maxW={maxW} selected={selected} {...data}>
        <div className="flex flex-col gap-3 space-y-0">
          {/* Request Configuration */}
          {requiredInputs.length > 0 && (
            <CollapsibleSection
              title={t('workflow.node.basic_config')}
              subtitle={`${t('workflow.node.basic_config_desc')}(${requireText})`}
              isExpanded={expandedSection.includes('input')}
              onToggle={() => toggleSection('input')}
              type="input"
              // tag={invalidCount > 0 ? `还有${invalidCount}个必填项未配置` : undefined}
            >
              <div className="space-y-2">
                {isTool && <RenderToolInput nodeId={nodeId} inputs={inputs} />}
              </div>
              {requiredInputs.length > 0 && (
                <RenderInput nodeId={nodeId} flowInputList={requiredInputs} />
              )}
            </CollapsibleSection>
          )}
          {/* Parameters Configuration */}
          {optionalInputs.length > 0 && (
            <CollapsibleSection
              title={t('workflow.node.variable_config')}
              subtitle={t('workflow.node.variable_config_desc')}
              isExpanded={expandedSection.includes('params')}
              onToggle={() => toggleSection('params')}
              type="params"
            >
              <div className="space-y-2">
                <RenderInput nodeId={nodeId} flowInputList={optionalInputs} />
              </div>
            </CollapsibleSection>
          )}
          <div className="pb-3">
            {outputs.filter((output) => output.type !== FlowNodeOutputTypeEnum.hidden).length >
              0 && (
              <CollapsibleSection
                title={t('workflow.node.output')}
                subtitle={t('workflow.node.output_desc')}
                isExpanded={expandedSection.includes('output')}
                onToggle={() => toggleSection('output')}
                type="output"
              >
                {outputs.filter((output) => output.type !== FlowNodeOutputTypeEnum.hidden).length >
                  0 && (
                  <div className="px-2">
                    <RenderOutput nodeId={nodeId} flowOutputList={outputs} />
                  </div>
                )}
              </CollapsibleSection>
            )}
          </div>

          {/* Output Configuration */}
        </div>
      </NodeCard>
    );
  }, [splitToolInputs, inputs, nodeId, minW, maxW, selected, data, outputs, expandedSection]);

  return Render;
};

export default React.memo(NodeSimple);
